package com.xiachufang.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiachufang.app.common.Res;
import com.xiachufang.app.entity.Category;
import com.xiachufang.app.entity.LoopAd;
import com.xiachufang.app.service.CategoryService;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Resource
    private CategoryService categoryService;

    /**
     * 如果参数包含id则更新
     * 否则为新增，或者找不到这个id的时候，也是新增
     * @param category
     * @return
     */
    @PostMapping
    public Res<?> save(@RequestBody Category category) {
        categoryService.save(category);
        return Res.success();
    }

    @DeleteMapping("/{id}")
    public Res<?> delete(@PathVariable Integer id) {
        categoryService.delete(id);
        return Res.success();
    }

    @GetMapping("/tree")
    public Res<?> tree() {
        return Res.success(categoryService.findChildren());
    }

    @GetMapping
    public Res<?> all() {
        return Res.success(categoryService.list());
    }

    @GetMapping("/home")
    public Res<?> home() {
        return Res.success(categoryService.home());
    }

    @GetMapping("/page")
    public Res<?> page(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                       @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                       @RequestParam(required = false, defaultValue = "") String name) {
        name = "%" + name + "%";
        Pageable pageRequest = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Direction.DESC, "id"));
        return Res.success(categoryService.findPage(pageRequest, name));
    }
}
